<template>
  <div>
    <h1>详情页面</h1>
    <h2>{{ weibo.nickname }}:{{ weibo.content }}</h2>
    <p style="color: #666;font-size: 12px">{{ weibo.created }}</p>
    <hr>
    <el-input placeholder="说点儿啥..." v-model="c.content"></el-input>
    <el-button @click="comment()">评论</el-button>
    <hr>
    <div v-for="c in arr">
      <h3>{{ c.nickname }}评论说:{{ c.content }}</h3>
      <p style="font-size: 12px;color: #666">{{ c.created }}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: "DetailView",
  data() {
    return {
      weibo: {}, c: {content: ""},
      arr: []
    }
  },
  methods: {
    loadCommentsById(id){
      //发请求获取和微博id相关的评论数据
      this.axios.get("http://localhost:8080/v1/comments/" + id)
          .then((response) => {
            if (response.data.code == 1) {
              this.arr = response.data.data;
            } else {
              this.$message.error(response.data.msg);
            }
          })
    },
    comment() {
      //让评论对象记录 源微博的id
      this.c.weiboId = this.weibo.id;
      //得到当前登录的用户对象
      let user = localStorage.user ? JSON.parse(localStorage.user) : null;
      if (user == null) {
        alert("请先登录!");
        this.$router.push('/login');
        return;
      }
      this.c.userId = user.id;//让评论对象记录用户id
      // name=张三&age=18&xxx=xxxx 查询字符串格式
      let data = this.qs.stringify(this.c);
      this.axios.post("http://localhost:8080/v1/comments/add-new", data)
          .then((response) => {
            if (response.data.code == 1) {
              this.$message.success("评论成功!");
              //加载评论
              this.loadCommentsById(this.weibo.id);
            } else {
              this.$message.error(response.data.msg);
            }
          })
    }
  },
  mounted() {
    //得到地址栏中的id
    let id = new URLSearchParams(location.search).get("id");

    this.loadCommentsById(id);

    //发请求获取id对应的微博信息
    this.axios.get("http://localhost:8080/v1/weibos/" + id)
        .then((response) => {
          if (response.data.code == 1) {
            this.weibo = response.data.data; //得到服务器响应的微博对象
          }
        })

  }
}
</script>

<style scoped>

</style>